package org.iks.common.pojo.message;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author kzou
 * @date 2024/1/2 21:53
 * @description: 序列化类型
 */
@Slf4j
@AllArgsConstructor
public enum SerializationType {

    JSON((byte) 1) {
        @Override
        public byte[] serialization(Object msg) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                String json = mapper.writeValueAsString(msg);
                return json.getBytes(StandardCharsets.UTF_8);
            } catch (Exception e) {
                log.error("json serialization exception {}", e.getMessage());
                return new byte[0];
            }
        }

        @Override
        public <T> T deserialization(byte[] data, Class<T> clazz) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                return mapper.readValue(data, clazz);
            } catch (Exception e) {
                log.error("json deserialization exception {}", e.getMessage());
                return null;
            }
        }
    },

    ;

    @Getter
    private final byte code;

    public abstract byte[] serialization(Object msg);

    public abstract <T> T deserialization(byte[] data, Class<T> clazz);

    public static SerializationType of(byte code) {
        for (SerializationType value : SerializationType.values()) {
            if (Objects.equals(value.getCode(), code)) {
                return value;
            }
        }
        log.warn("not found serializationType for {}", code);
        return null;
    }
}
